package itbour.onetouchshow.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.callback.DownloadSubscriber;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.utils.HttpUtils;
import com.lsjr.utils.NetUtils;
import com.umeng.analytics.AnalyticsConfig;

import java.io.File;
import java.util.HashMap;

import itbour.onetouchshow.bean.DeviceInfoV57Bean;
import itbour.onetouchshow.bean.UpApkInfoV57Bean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.widget.OneTouchProgressDialog;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * Created by Administrator on 2018/1/9.
 */

public class AppCommNetUtils {


    //本方法用于提示是否需要更新 0 代表 首页 1代表setting界面
    //返回 0代表没有更新 1代表有更新
    public static void checkIsNeedUpData(final Activity context) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        //渠道号
        String channelName = AnalyticsConfig.getChannel(context);
        //app版本
        String appVersionName = DeviceUtil.getAppVersionName(UIUtils.getContext());
        //手机型号
        String model = Build.MODEL;
        //系统版本
        String release = Build.VERSION.RELEASE;
        //来自android
        DeviceInfoV57Bean deviceInfoV57Bean = new DeviceInfoV57Bean();
        deviceInfoV57Bean.setAppVersion(appVersionName);
        deviceInfoV57Bean.setChannel(channelName);
        deviceInfoV57Bean.setDevice(AppConst.ANDROID_DEVICE);
        deviceInfoV57Bean.setDeviceType(release + " " + model);
        deviceInfoV57Bean.setSystemVersion(model);
        String deviceInfoV57Json = new Gson().toJson(deviceInfoV57Bean);
        //如果是来自印刷品的修改 那么请求预览接口
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("deviceInfo", deviceInfoV57Json);

        HttpUtils.getInstance().executeGet(AppConfig.GETLASTVERSION_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {

            }

            @Override
            protected void onSuccess(String response) {
                L_.e(response);
                UpApkInfoV57Bean upApkInfoV57Bean = new Gson().fromJson(response, UpApkInfoV57Bean.class);
                // int success = upApkInfoV57Bean.getSuccess();
                String lastVersion = upApkInfoV57Bean.getLastVersion();
                int i = CommonUtils.compareVersion(lastVersion, appVersionName);
                if (i == 1) {
                    final String apkUrl = upApkInfoV57Bean.getApkUrl();
                    final String upgradeUrl = upApkInfoV57Bean.getUpgradeUrl();
                    doDonwload(context, apkUrl);
                } else {//没有更新的情况 且来自设置界面 点击版本更新时候调用

                }

            }
        });

    }

    private static void doDonwload(final Activity context, String url) {
        // File outputfile = new File(UIUtils.getContext().getExternalCacheDir(), "output.mp4");

        String name = DateUtils.getYMD() + FileUtils.getFileName(url);
        //先查找本地   必须保证在我们自己的目录下打开才能找到  如果自己发出相当于重新下载一次
//        boolean downLoad = true;
//        if (AppCache.getInstance().fileExists(AppCache.getInstance().mFilesDir, name)) {
//            downLoad = false;
//        }

        OneTouchProgressDialog oneTouchProgressDialog = new OneTouchProgressDialog();
        oneTouchProgressDialog.setTitle("正在下载");
        oneTouchProgressDialog.builderApk(context);

        L_.e("下载文件" + name);
        HttpUtils.getInstance().downloadFile(url, new DownloadSubscriber(UIUtils.getContext(),
                null, name) {
            @Override
            public void onComplete(String path) {
                L_.e("文件保存路径：" + path);
                T_.showCustomToast("文件保存路径：" + path);

                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        installApk(context, new File(path));
                        context.finish();
                    }
                });


            }

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                L_.e(progress + "% ");
                oneTouchProgressDialog.getTvprogress().setText(progress + "% ");
                oneTouchProgressDialog.getProgressBar().setProgress(progress);
                if (progress == 100) {
                    oneTouchProgressDialog.dismiss();
                    context.finish();
                }
            }

            @Override
            protected void onXError(String exception) {
                L_.e(exception + "% ");
                T_.showToastReal(exception);
                context.finish();

            }
        });
    }


    /**
     * 安装apk
     */
    protected static void installApk(Context context, File file) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(context, "itbour.onetouchshow.fileprovider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setAction(Intent.ACTION_VIEW);
            //执行的数据类型
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    //static ComplexDialogFrag complexDialogFrag;

    @SuppressLint("ValidFragment")
    public static void showUpgrade(Activity activity) {
//        complexDialogFrag = new ComplexDialogFrag() {
//            @Override
//            public Builder setBuilder() {
//                return new Builder().setTitle("")
//                        .setCancletext("取消").setCancleListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                complexDialogFrag.dismiss();
//                                activity.finish();
//                            }
//                        })
//                        .setConfirmText("立即升级").setConfirmListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                if (NetUtils.isConnected(activity)) {
//                                    complexDialogFrag.dismiss();
//                                    AppCommNetUtils.checkIsNeedUpData(activity);
//                                }
//                            }
//                        }).setContext("您的一键秀版本过低，请升级到最新版本使用").setPlatform(DialogPlatform.TWO_BTN);
//            }
//        };
//        complexDialogFrag.show(activity.getFragmentManager().beginTransaction(), null);
//
//

        new OneToucDialog.Builder(activity)
                .content("您的一键秀版本过低，请升级到最新版本使用")
                .positiveText("立即升级").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                if (NetUtils.isConnected(activity)) {
                    AppCommNetUtils.checkIsNeedUpData(activity);
                }
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                activity.finish();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();

    }

}
